<template>
    <view class="page">
        <view class="ing" v-if="!reqsItem.taskId">
            <!--        <view class="ing" v-if="!reqsItem.taskId"> -->
            <view class="title">
                <text class="tel">正在生成中，请耐心等待...</text>
                <text class="status">{{ reqsItem.progress ?? 0 }}%</text>
            </view>
            <view class="progress-container">
                <view class="content">
                    <uv-line-progress :percentage="reqsItem.progress ?? 0" height="4"
                        :showText="false"></uv-line-progress>
                </view>
            </view>
            <view class="tip-container">
                <view class="tip">提示：中途离开本页面不影响创作</view>
                <view class="tip">绘图完成请前往【我的】-我的作品查看结果</view>
            </view>
        </view>

        <view class="content" v-if="reqsItem.taskId">
            <swiper class="swiper" circular autoplay interval="5000" current="0" @change="intervalChange">
                <swiper-item class="swiper-item" v-for="(item, i) in daubInfo.detailsList" :key="i">
                    <view class="swiper-item">
                        <uv-image v-if="item" class="swiper-item-img" :src="item" mode="aspectFit" width="100%"
                            height="100%" @click="previewImage"></uv-image>
                        <view class="block" v-else>
                            <uv-icon class="block-icon" name="info-circle-fill" color="#999" size="40"></uv-icon>
                            <text class="text">本次生成图片可能有些偏差！</text>
                            <text class="text">请尝试重新生成</text>
                        </view>
                    </view>
                </swiper-item>
            </swiper>
        </view>

        <view class="btn-conainer " v-if="daubInfo.id && daubInfo.downLoadList.length">
            <view class="high" @click="download">下载结果图</view>
            <view class="down" @click="reDaub">重新修改</view>
        </view>

        <!-- 控制器 -->
        <view class="controller" v-if="reqsItem.taskId">
            <view class="work-btn-style btn" @click="daubImg">
                <text class="btn-text">点击生成</text>
                <text class="btn-price">（本次消耗{{ cost }}点积分）</text>
            </view>
        </view>

        <!-- loading -->
        <uv-loading-page :loading="loading" :loadingText="loadingText" font-size="24rpx"
            bgColor="rgba(0,0,0,0.5)"></uv-loading-page>

        <fab :type="fabType" />
    </view>
</template>

<script setup>
import {
    onLoad,
    onHide
} from '@dcloudio/uni-app'
import {
    ref
} from 'vue';
import {
    downloadImg,
    previewModel
} from "@/utils/utils.js";

import {
    apiGetReqsStatus,
    BASE_URL,
    apiDrawInpaintCreation
} from '@/api/defaultApi.js'


//pinia
import {
    storeToRefs
} from 'pinia'
import {
    useUserStore
} from "@/stores/useUserStore.js"
import {
    useLoadingStore
} from "@/stores/useLoadingStore.js"

// 获取pinia的数据
const userStore = useUserStore()
const loadingStore = useLoadingStore()

// 从pinia的数据中结构出值并做响应式
const {
    token
} = storeToRefs(userStore)
const {
    loading
} = storeToRefs(loadingStore)

const id = ref('')
const filedata = ref('')
const prompt = ref('')
const sketch_image = ref('')            // 绘制结果base64地址

const reqsItem = ref({})            //任务结果对象
const daubInfo = ref({})            //结果的详细信息
const index = ref(0)

const cost = ref(0)                 //消耗积分数量

//定时器
const count = ref(100000)

const loadingText = ref('图片上传中...')

const fabType = ref('index')


onLoad((option) => {
    id.value = option.id
    let jsnoForm = JSON.parse(option.formData)
    filedata.value = jsnoForm.filedata
    prompt.value = jsnoForm.prompt
    cost.value = jsnoForm.cost
    sketch_image.value = decodeURIComponent(jsnoForm.sketch_image)



    const timer = setInterval(() => {
        getReqsStatus()
        count.value = count.value - 1

        if (reqsItem.value.taskId || count.value == 0) {
            clearInterval(timer)
        }

    }, 3000)
})

// 获取涂抹替换任务状态
const getReqsStatus = async () => {
    let res = await apiGetReqsStatus({
        id: id.value,
        type: 'inpaint'
    })
    reqsItem.value = res.data
    if (res.data?.resultStatistics?.block_num > 0) {
        for (let index = 0; index < res.data?.resultStatistics?.block_num; index++) {
            reqsItem.value.resultImages.push('')
        }
    }
    if (reqsItem.value.progress == 100) {
        fabType.value = 'user'
    }

    if (reqsItem.value.taskId) {
        getDrawInpaintCreation(reqsItem.value.taskId)
    }

}

//获取结果详情
const getDrawInpaintCreation = async (id) => {
    let res = await apiDrawInpaintCreation(id)
    daubInfo.value = res.data[0]
}

// 记录index
const intervalChange = (e) => {
    index.value = e.detail.current
}

// 预览图片
const previewImage = () => {
    previewModel(daubInfo.value.detailsList, index.value)
}

//下载图片
const download = async () => {
    loadingText.value = '图片获取中...'
    loadingStore.setLoading(true)

    downloadImg(daubInfo.value.downLoadList[index.value])

}

// 生成
const daubImg = async () => {
    if (!filedata.value) {
        return
    }

    uni.uploadFile({
        url: BASE_URL + '/inpaint/draw_inpaint',
        filePath: filedata.value,
        name: 'filedata',
        header: {
            Authorization: 'bearer ' + token.value,
        },
        formData: {
            'sketch_image': sketch_image.value,
            'prompt': prompt.value
        },
        success(res) {

            const data = JSON.parse(res.data).data

            if (res.statusCode === 401) {
                uni.showToast({
                    title: "请登录后进行操作",
                    icon: "none",
                    success: () => {
                        setTimeout(() => {
                            uni.navigateTo({
                                url: '/pages/login/login'
                            })
                        }, 500)
                    }
                })
                return
            }
            if (res.statusCode === 500) {
                uni.showToast({
                    title: data.msg,
                    icon: "none",
                    showCancel: false,
                    confirmColor: '#000',
                    duration: 3000
                })
                return
            }


            let form = {
                'filedata': filedata.value,
                'sketch_image': sketch_image.value,
                'prompt': prompt.value,
                'cost': cost.value
            }



            if (JSON.parse(res.data).code === 0) {
                uni.redirectTo({
                    url: '/pages/daubInfo/daubInfo?id=' + data + '&formData=' + JSON
                        .stringify(form)
                })
            }
        },
        fail: function (err) {
            uni.showModal({
                content: "空间图片已丢失，请点击返回按钮并重新上传空间图片",
                icon: "none",
                confirmText: '返回',
                success: function (res) {
                    if (res.confirm) {
                        uni.reLaunch({
                            url: '/pages/daub/daub'
                        });
                    }
                }
            })
        },
        complete: function () {
            loadingStore.setLoading(false)
        }
    })


}

// 重新生成
const reDaub = () => {
    uni.navigateBack({
        delta: 1
    });
}



</script>

<style lang="scss" scoped>
.ing {
    margin: 284rpx auto 0;
    width: 480rpx;

    .title {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        height: 22rpx;
        line-height: 22rpx;
        font-size: 22rpx;
        color: #e6e6e6;
        font-weight: 400;
        margin-bottom: 20rpx;
    }

    .progress-container {
        width: 100%;
        height: 32rpx;
        background: linear-gradient(0deg, #ff8a63 0%, #ffde7d 100%);
        border-radius: 5rpx;
        display: flex;
        justify-content: center;
        align-items: center;

        .content {
            height: 28rpx;
            width: calc(100% - 4rpx);
            background: #000;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 0 12rpx;

            &:deep(.uv-line-progress) {

                // .uv-line-progress__background{
                //     background: linear-gradient(0deg,#ff8a63 0%, #ffde7d 100%) !important;
                // }
                .uv-line-progress__line {
                    background: linear-gradient(0deg, #ff8a63 0%, #ffde7d 100%) !important;
                }
            }
        }
    }
        
    .tip-container{
        margin-top: 200rpx;
        .tip{
            color: #fff;
            font-size: 24rpx;
            line-height: 40rpx;
            width: 100%;
            display: flex;
            justify-content: center;
        }
    }
}

.content {
    width: 686rpx;
    margin: 0 auto;

    .swiper {
        width: 100%;
        height: 514rpx;
        border-radius: 20rpx;
        overflow: hidden;
        background: #191919;

        .swiper-item {
            height: 100%;

            .swiper-item-img {
                width: 100%;
                height: 100%;
            }

            .block {
                width: 100%;
                height: 100%;
                background: #191919;
                display: flex;
                flex-direction: column;
                align-items: center;

                .block-icon {
                    margin-top: 140rpx;
                }

                .text {
                    margin-top: 40rpx;
                    color: #fff;
                    font-size: 24rpx;
                    width: 100%;
                    text-align: center;
                }
            }
        }
    }
}

.btn-conainer {
    width: 100%;
    height: 72rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: #000;
    font-size: 24rpx;
    font-weight: 700;
    margin-top: 40rpx;

    .high {
        width: 480rpx;
        height: 72rpx;
        background: #ffcb30;
        border-radius: 20rpx;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .down {
        width: 176rpx;
        height: 72rpx;
        background: #e6e6e6;
        border-radius: 20rpx;
        display: flex;
        align-items: center;
        justify-content: center;
    }
}


.controller {
    height: 122rpx;
    width: 100%;
    background: #000;
    position: fixed;
    bottom: var(--window-bottom);
    left: 0;
    padding: 0 32rpx;
    box-sizing: border-box;
    z-index: 9;

    .btn {
        width: 100%;
        height: 78rpx;
        border-radius: 39rpx;
        color: #080808;
        align-items: flex-end;
        margin: 20rpx auto;

        .btn-text {
            font-size: 30rpx;
            font-weight: 700;
            line-height: 78rpx;
        }

        .btn-price {
            font-weight: 500;
            font-size: 18rpx;
            line-height: 60rpx;
            letter-spacing: 2.8rpx;
        }
    }
}
</style>
